<template>
  <VPage>
    <div class="p-[16px] w-[100%]">
      <p class="text-[14px] leading-[20px] my-[16px] flex">
        <span class="font-[600]">1</span>：点击下载模版
        <span class="flex items-center ml-[16px]" @click="handleDownload">
          <el-icon> <Download /> </el-icon>下载模板
        </span>
      </p>
      <p class="text-[14px] leading-[20px] my-[16px] flex">
        <span class="mt-[6px]"> <span class="font-[600]">2</span>：上传填写完成的文件 </span>
        <span>
          <el-upload
            ref="upload"
            v-model:file-list="fileList"
            accept=".xlsx"
            class="v-import ml-[16px]"
            :data="extraData"
            :auto-upload="false"
            :limit="1"
            :action="ossParams.host || ''"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :on-progress="handleUploadProgress"
            :on-error="handleUploadError"
            :on-change="handleChange"
            :on-success="handleUploadSuccess"
          >
            <VButton type="primary">上传文件</VButton>
          </el-upload>
        </span>
      </p>
      <div class="text-[14px] leading-[20px] my-[16px] flex items-center">
        <div class="font-[600]">3</div>
        ：导入结果： 总订单数：
        <div class="text-[18px]">{{ importForm.order_num || 0 }}</div>
        单，成功：
        <div class="text-[#3487ff] text-[18px]">{{ importForm.success_num || 0 }}</div>
        单，失败：
        <div class="text-[#ff0000] text-[18px]">{{ importForm.failed_num || 0 }}</div>
        单
        <VButton type="primary" class="ml-[16px]" @click="onHandleDownload">导出导入结果</VButton>
      </div>
      <el-divider />
      <div class="flex top-border">
        <div class="w-[50px]">
          <p>说明：</p>
        </div>
        <div class="flex-1">
          <p>1. 平台、店铺填写：与系统平台站点店铺一致；</p>
          <p>2. 币种、国家填写：英文简写（例如：CNY、CN）；</p>
          <p>3. 当订单存在多个SKU时，在模板中分多行填写，除商品信息外，其他订单信息保持一致；</p>
          <p>4. 导入订单根据店铺和平台订单号区分是否为同一订单；</p>
          <p>5. 订单支付金额=sum（SKU销售收入+SKU运费收入-优惠金额）；</p>
          <p>6. 导入结果也可在“个人中心-导出中心”查看；</p>
        </div>
      </div>
    </div>
  </VPage>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus"
import { uploadSignUrl } from "@/api/public"
import api from "../list/api"
import { exportRecordDownload } from "@/api"
import action from "@/utils/action.js"
const downloadUrl = ref("/import/order/订单导入模板.xlsx")
let ossParams = reactive({
  host: "",
})
onMounted(() => {
  console.log()
  initUpload()
})

const initUpload = async () => {
  const { data } = await uploadSignUrl({ dir: "import/order/" })
  console.warn(data)
  ossParams = {
    ...data?.signature,
  }
}
const handleDownload = async () => {
  const { data } = await api.getImportTpl({ tpl_name: `订单导入模板${import.meta.env.MODE != "production" ? "_dev" : ""}.xlsx` })
  if (data.url) {
    window.open(data.url, "noopener", "noreferrer")
  }
}

const extraData = reactive({})
const uploadPercent = ref(0)

let loadings = reactive({})

const fileList = ref([])
const fileName = ref("")
const remark = ref("")
const upload = ref()

const handleExceed = (files) => {
  upload.value?.clearFiles()
  const file = files[0]
  upload.value?.handleStart(file)
}
const get_suffix = (name) => {
  const pos = name.lastIndexOf(".")
  let suffix = ""
  if (pos != -1) {
    suffix = name.substring(pos)
  }
  return suffix
}
const handleChange = async (file) => {
  await initUpload()
  upload.value.submit()
}
const fileNames = ref("")
const beforeUpload = async (file) => {
  if (file.size > 1024 * 1024 * 1024) {
    ElMessage.warning("上传文件大小不能超过1G")
    return false
  }
  uploadPercent.value = 0
  try {
    console.log(11111)
    const { policy, accessid, dir, signature, callback } = ossParams || {}
    console.warn(file)
    const name = `${file.name.split(".")[0]}${+new Date()}`
    const _fileName = name + get_suffix(file.name)
    fileNames.value = "import/order/" + _fileName
    extraData.key = dir + _fileName
    extraData.policy = policy
    extraData.OSSAccessKeyId = accessid
    extraData.signature = signature
    fileName.value = _fileName
    console.log(22222)
    console.log(extraData)
    return true
  } catch (err) {
    fileName.value = ""
    console.log(err)
    ElMessage.error(err.message)
    return false
  }
}

const handleUploadProgress = (e) => {
  uploadPercent.value = parseInt(e.percent)
}

const handleUploadError = (err) => {
  fileName.value = ""
  ElMessage.error(`上传失败 ${err.toString()}`)
  uploadPercent.value = 0
}
const importForm = ref({})
const handleUploadSuccess = (res, file, fileList) => {
  ElMessage.success("上传成功")
  api.batchImport({ oss_url: fileNames.value }).then((res) => {
    importForm.value = res.data
  })
}
const onHandleDownload = async () => {
  if (!importForm.value.task_id) return

  // const { data } = await exportRecordDownload({ id: importForm.value.task_id })
  // if (data?.url) {
  //   window.open(data.url, "noopener", "noreferrer")
  // }
  ElMessageBox.confirm("导出成功，是否跳转导出中心下载文件！", "", {
    confirmButtonText: "跳转",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      action.setGlobalState({
        changeMicoTabsPath: {
          path: "/user/profile",
          type: "push",
        },
      })
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消" })
    })
}
const submit = async () => {
  loadings.submit = true
  try {
    if (!fileName.value) {
      ElMessage.warning("请检查文件是否上传")
      return
    }
    await expenseCustomImport({
      oss_name: fileName.value,
      oss_url: `${ossParams.dir}${fileName.value}`,
    })
    handleClose(true)
  } catch (e) {
    console.error(e)
  } finally {
    loadings.submit = false
  }
}
</script>
<style lang="scss" scoped>
.v-import {
  display: flex;
  :deep(.el-upload-dragger) {
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    // border-color: #3366f1;
  }
  :deep(.el-upload-list) {
    margin-top: 5px;
  }
}
.top-border {
  // border-top: 1px solid #dadada;
  // padding-top: 16px;
  p {
    line-height: 30px;
  }
}
</style>
